<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
<meta name="theme-color" content="#222">
<meta name="generator" content="Hexo 4.2.0">
  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png">
  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png">
  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png">
  <link rel="mask-icon" href="/images/logo.svg" color="#222">

<link rel="stylesheet" href="/css/main.css">


<link rel="stylesheet" href="/lib/font-awesome/css/font-awesome.min.css">


<script id="hexo-configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    hostname: new URL('http://yoursite.com').hostname,
    root: '/',
    scheme: 'Pisces',
    version: '7.6.0',
    exturl: false,
    sidebar: {"position":"left","display":"post","padding":18,"offset":12,"onmobile":false},
    copycode: {"enable":false,"show_result":false,"style":null},
    back2top: {"enable":true,"sidebar":false,"scrollpercent":false},
    bookmark: {"enable":false,"color":"#222","save":"auto"},
    fancybox: false,
    mediumzoom: false,
    lazyload: false,
    pangu: false,
    comments: {"style":"tabs","active":null,"storage":true,"lazyload":false,"nav":null},
    algolia: {
      appID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    },
    localsearch: {"enable":false,"trigger":"auto","top_n_per_article":1,"unescape":false,"preload":false},
    path: '',
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}}
  };
</script>

  <meta name="description" content="功能Redis对内存管理进行啦封装，可以根据自己的实际情况选择不同的库对内存进行分配管理。Redis封装啦以下函数123456789101112131415void *zmalloc(size_t size);void *zcalloc(size_t size);void *zrealloc(void *ptr, size_t size);void zfree(void *ptr);char *z">
<meta property="og:type" content="article">
<meta property="og:title" content="Redis 内存管理">
<meta property="og:url" content="http://yoursite.com/2020/06/01/Redis-%E5%86%85%E5%AD%98%E7%AE%A1%E7%90%86/index.html">
<meta property="og:site_name" content="SRCNN">
<meta property="og:description" content="功能Redis对内存管理进行啦封装，可以根据自己的实际情况选择不同的库对内存进行分配管理。Redis封装啦以下函数123456789101112131415void *zmalloc(size_t size);void *zcalloc(size_t size);void *zrealloc(void *ptr, size_t size);void zfree(void *ptr);char *z">
<meta property="og:locale" content="en_US">
<meta property="article:published_time" content="2020-06-01T02:34:36.000Z">
<meta property="article:modified_time" content="2020-06-03T06:46:11.137Z">
<meta property="article:author" content="Z.J. Jiang">
<meta property="article:tag" content="SISR">
<meta property="article:tag" content=" FH">
<meta name="twitter:card" content="summary">

<link rel="canonical" href="http://yoursite.com/2020/06/01/Redis-%E5%86%85%E5%AD%98%E7%AE%A1%E7%90%86/">


<script id="page-configurations">
  // https://hexo.io/docs/variables.html
  CONFIG.page = {
    sidebar: "",
    isHome: false,
    isPost: true
  };
</script>

  <title>Redis 内存管理 | SRCNN</title>
  






  <noscript>
  <style>
  .use-motion .brand,
  .use-motion .menu-item,
  .sidebar-inner,
  .use-motion .post-block,
  .use-motion .pagination,
  .use-motion .comments,
  .use-motion .post-header,
  .use-motion .post-body,
  .use-motion .collection-header { opacity: initial; }

  .use-motion .site-title,
  .use-motion .site-subtitle {
    opacity: initial;
    top: initial;
  }

  .use-motion .logo-line-before i { left: initial; }
  .use-motion .logo-line-after i { right: initial; }
  </style>
</noscript>

</head>

<body itemscope itemtype="http://schema.org/WebPage">
  <div class="container use-motion">
    <div class="headband"></div>

    <header class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-container">
  <div class="site-meta">

    <div>
      <a href="/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">SRCNN</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
        <p class="site-subtitle">SISR-FH</p>
  </div>

  <div class="site-nav-toggle">
    <div class="toggle" aria-label="Toggle navigation bar">
      <span class="toggle-line toggle-line-first"></span>
      <span class="toggle-line toggle-line-middle"></span>
      <span class="toggle-line toggle-line-last"></span>
    </div>
  </div>
</div>


<nav class="site-nav">
  
  <ul id="menu" class="menu">
        <li class="menu-item menu-item-home">

    <a href="/" rel="section"><i class="fa fa-fw fa-home"></i>Home</a>

  </li>
        <li class="menu-item menu-item-tags">

    <a href="/tags/" rel="section"><i class="fa fa-fw fa-tags"></i>Tags</a>

  </li>
        <li class="menu-item menu-item-categories">

    <a href="/categories/" rel="section"><i class="fa fa-fw fa-th"></i>Categories</a>

  </li>
        <li class="menu-item menu-item-archives">

    <a href="/archives/" rel="section"><i class="fa fa-fw fa-archive"></i>Archives</a>

  </li>
  </ul>

</nav>
</div>
    </header>

    
  <div class="back-to-top">
    <i class="fa fa-arrow-up"></i>
    <span>0%</span>
  </div>


    <main class="main">
      <div class="main-inner">
        <div class="content-wrap">
          

          <div class="content">
            

  <div class="posts-expand">
      
  
  
  <article itemscope itemtype="http://schema.org/Article" class="post-block " lang="en">
    <link itemprop="mainEntityOfPage" href="http://yoursite.com/2020/06/01/Redis-%E5%86%85%E5%AD%98%E7%AE%A1%E7%90%86/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/images/avatar.gif">
      <meta itemprop="name" content="Z.J. Jiang">
      <meta itemprop="description" content="about the single image super-resolution and face hallucination">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="SRCNN">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">
          Redis 内存管理
        </h1>

        <div class="post-meta">
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              <span class="post-meta-item-text">Posted on</span>

              <time title="Created: 2020-06-01 10:34:36" itemprop="dateCreated datePublished" datetime="2020-06-01T10:34:36+08:00">2020-06-01</time>
            </span>
              <span class="post-meta-item">
                <span class="post-meta-item-icon">
                  <i class="fa fa-calendar-check-o"></i>
                </span>
                <span class="post-meta-item-text">Edited on</span>
                <time title="Modified: 2020-06-03 14:46:11" itemprop="dateModified" datetime="2020-06-03T14:46:11+08:00">2020-06-03</time>
              </span>
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              <span class="post-meta-item-text">In</span>
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/Redis/" itemprop="url" rel="index">
                    <span itemprop="name">Redis</span>
                  </a>
                </span>
            </span>

          

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">

      
        <h1 id="功能"><a href="#功能" class="headerlink" title="功能"></a>功能</h1><p>Redis对内存管理进行啦封装，可以根据自己的实际情况选择不同的库对内存进行分配管理。Redis封装啦以下函数<br><figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">void</span> *<span class="title">zmalloc</span><span class="params">(<span class="keyword">size_t</span> <span class="built_in">size</span>)</span></span>;</span><br><span class="line"><span class="function"><span class="keyword">void</span> *<span class="title">zcalloc</span><span class="params">(<span class="keyword">size_t</span> <span class="built_in">size</span>)</span></span>;</span><br><span class="line"><span class="function"><span class="keyword">void</span> *<span class="title">zrealloc</span><span class="params">(<span class="keyword">void</span> *ptr, <span class="keyword">size_t</span> <span class="built_in">size</span>)</span></span>;</span><br><span class="line"><span class="function"><span class="keyword">void</span> <span class="title">zfree</span><span class="params">(<span class="keyword">void</span> *ptr)</span></span>;</span><br><span class="line"><span class="function"><span class="keyword">char</span> *<span class="title">zstrdup</span><span class="params">(<span class="keyword">const</span> <span class="keyword">char</span> *s)</span></span>;</span><br><span class="line"><span class="keyword">size_t</span> zmalloc_used_memory(<span class="keyword">void</span>);</span><br><span class="line"><span class="function"><span class="keyword">void</span> <span class="title">zmalloc_set_oom_handler</span><span class="params">(<span class="keyword">void</span> (*oom_handler)(<span class="keyword">size_t</span>))</span></span>;</span><br><span class="line"><span class="keyword">size_t</span> zmalloc_get_rss(<span class="keyword">void</span>);</span><br><span class="line"><span class="function"><span class="keyword">int</span> <span class="title">zmalloc_get_allocator_info</span><span class="params">(<span class="keyword">size_t</span> *allocated, <span class="keyword">size_t</span> *active, <span class="keyword">size_t</span> *resident)</span></span>;</span><br><span class="line"><span class="function"><span class="keyword">void</span> <span class="title">set_jemalloc_bg_thread</span><span class="params">(<span class="keyword">int</span> enable)</span></span>;</span><br><span class="line"><span class="function"><span class="keyword">int</span> <span class="title">jemalloc_purge</span><span class="params">()</span></span>;</span><br><span class="line"><span class="keyword">size_t</span> zmalloc_get_private_dirty(<span class="keyword">long</span> pid);</span><br><span class="line"><span class="keyword">size_t</span> zmalloc_get_smap_bytes_by_field(<span class="keyword">char</span> *field, <span class="keyword">long</span> pid);</span><br><span class="line"><span class="keyword">size_t</span> zmalloc_get_memory_size(<span class="keyword">void</span>);</span><br><span class="line"><span class="function"><span class="keyword">void</span> <span class="title">zlibc_free</span><span class="params">(<span class="keyword">void</span> *ptr)</span></span></span><br></pre></td></tr></table></figure><br><a id="more"></a></p>
<h1 id="函数分析"><a href="#函数分析" class="headerlink" title="函数分析"></a>函数分析</h1><h2 id="zmalloc-default-oom"><a href="#zmalloc-default-oom" class="headerlink" title="zmalloc_default_oom"></a>zmalloc_default_oom</h2><p>oom表示out of memory.此函数在分配内存空间失败时打印错误信息。当然也可调用<strong>zmalloc_set_oom_handler</strong>使用自定义的错误输出函数.<br><figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">static</span> <span class="keyword">void</span> <span class="title">zmalloc_default_oom</span><span class="params">(<span class="keyword">size_t</span> <span class="built_in">size</span>)</span> </span>&#123;</span><br><span class="line">    <span class="built_in">fprintf</span>(<span class="built_in">stderr</span>, <span class="string">"zmalloc: Out of memory trying to allocate %zu bytes\n"</span>,</span><br><span class="line">        <span class="built_in">size</span>);</span><br><span class="line">    fflush(<span class="built_in">stderr</span>);</span><br><span class="line">    <span class="built_in">abort</span>();</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<h2 id="内存统计函数"><a href="#内存统计函数" class="headerlink" title="内存统计函数"></a>内存统计函数</h2><p>内存统计函数使用一个全局变量used_memory来记录已开辟的内存。使用原子操作更新已使用内存值。__atomic_add_fetch是C++11支持的函数，如果没有的话则使用线程锁的方式。其中，_n&amp;(sizeof(long)-1) = _n % sizeof(long) - 1，用位操作来优化求余操作，之所要要这样，是因为内存需要对齐。值得注意的是这边的宏使用啦do{}while(0)的技巧。<br><figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">#<span class="meta-keyword">define</span> update_zmalloc_stat_alloc(__n) do &#123; \</span></span><br><span class="line">    <span class="keyword">size_t</span> _n = (__n); \</span><br><span class="line">    <span class="keyword">if</span> (_n&amp;(<span class="keyword">sizeof</span>(<span class="keyword">long</span>)<span class="number">-1</span>)) _n += <span class="keyword">sizeof</span>(<span class="keyword">long</span>)-(_n&amp;(<span class="keyword">sizeof</span>(<span class="keyword">long</span>)<span class="number">-1</span>)); \</span><br><span class="line">    atomicIncr(used_memory,__n); \</span><br><span class="line">&#125; <span class="keyword">while</span>(<span class="number">0</span>)</span><br><span class="line"></span><br><span class="line"><span class="comment">// __atomic_add_fetch方式</span></span><br><span class="line"><span class="meta">#<span class="meta-keyword">define</span> atomicIncr(var,count) __atomic_add_fetch(&amp;var,(count),__ATOMIC_RELAXED)</span></span><br><span class="line"></span><br><span class="line"><span class="comment">// 线程锁的方式</span></span><br><span class="line"><span class="meta">#<span class="meta-keyword">define</span> atomicIncr(var,count) do &#123; \</span></span><br><span class="line">    pthread_mutex_lock(&amp;var ## _mutex); \</span><br><span class="line">    var += (count); \</span><br><span class="line">    pthread_mutex_unlock(&amp;var ## _mutex); \</span><br><span class="line">&#125; <span class="keyword">while</span>(<span class="number">0</span>)</span><br></pre></td></tr></table></figure></p>
<h2 id="zmalloc-zcolloc-zrealloc-zfree"><a href="#zmalloc-zcolloc-zrealloc-zfree" class="headerlink" title="zmalloc zcolloc zrealloc zfree"></a>zmalloc zcolloc zrealloc zfree</h2><p>zmalloc函数是malloc函数的封装，加上了一些错误处理和内存使用统计。同理zcolloc,zrealloc,zfree也是标准库函数的封装，加上错误处理和记录已分配内存的大小。<br><figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">void</span> *<span class="title">zmalloc</span><span class="params">(<span class="keyword">size_t</span> <span class="built_in">size</span>)</span> </span>&#123;</span><br><span class="line">    <span class="comment">// 分配空间</span></span><br><span class="line">    <span class="keyword">void</span> *ptr = <span class="built_in">malloc</span>(<span class="built_in">size</span>+PREFIX_SIZE);</span><br><span class="line"></span><br><span class="line">    <span class="keyword">if</span> (!ptr) zmalloc_oom_handler(<span class="built_in">size</span>);</span><br><span class="line"><span class="meta">#<span class="meta-keyword">ifdef</span> HAVE_MALLOC_SIZE</span></span><br><span class="line">    <span class="comment">// 更新状态</span></span><br><span class="line">    update_zmalloc_stat_alloc(zmalloc_size(ptr));</span><br><span class="line">    <span class="keyword">return</span> ptr;</span><br><span class="line"><span class="meta">#<span class="meta-keyword">else</span></span></span><br><span class="line">    *((<span class="keyword">size_t</span>*)ptr) = <span class="built_in">size</span>;</span><br><span class="line">    update_zmalloc_stat_alloc(<span class="built_in">size</span>+PREFIX_SIZE);</span><br><span class="line">    <span class="keyword">return</span> (<span class="keyword">char</span>*)ptr+PREFIX_SIZE;</span><br><span class="line"><span class="meta">#<span class="meta-keyword">endif</span></span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<h2 id="zstrup"><a href="#zstrup" class="headerlink" title="zstrup"></a>zstrup</h2><p>字符串复制函数，深拷贝！<br><figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">char</span> *<span class="title">zstrdup</span><span class="params">(<span class="keyword">const</span> <span class="keyword">char</span> *s)</span> </span>&#123;</span><br><span class="line">    <span class="keyword">size_t</span> l = <span class="built_in">strlen</span>(s)+<span class="number">1</span>;</span><br><span class="line">    <span class="keyword">char</span> *p = zmalloc(l);</span><br><span class="line"></span><br><span class="line">    <span class="built_in">memcpy</span>(p,s,l);</span><br><span class="line">    <span class="keyword">return</span> p;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<h2 id="zmalloc-used-memory"><a href="#zmalloc-used-memory" class="headerlink" title="zmalloc_used_memory"></a>zmalloc_used_memory</h2><p>查询Redis已经开辟的内存空间。<br><figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">size_t</span> zmalloc_used_memory(<span class="keyword">void</span>) &#123;</span><br><span class="line">    <span class="keyword">size_t</span> um;</span><br><span class="line">    atomicGet(used_memory,um);</span><br><span class="line">    <span class="keyword">return</span> um;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<h2 id="zmalloc-get-rss"><a href="#zmalloc-get-rss" class="headerlink" title="zmalloc_get_rss"></a>zmalloc_get_rss</h2><p>获得操作系统分配给redis的内存大小。rss(Resident Set Size)在/proc/pid号/stat 第第24个域。实际使用等于rss乘以一个页的大小。<br><figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">size_t</span> zmalloc_get_rss(<span class="keyword">void</span>) &#123;</span><br><span class="line">    <span class="keyword">int</span> page = sysconf(_SC_PAGESIZE);</span><br><span class="line">    <span class="keyword">size_t</span> rss;</span><br><span class="line">    <span class="keyword">char</span> buf[<span class="number">4096</span>];</span><br><span class="line">    <span class="keyword">char</span> filename[<span class="number">256</span>];</span><br><span class="line">    <span class="keyword">int</span> fd, count;</span><br><span class="line">    <span class="keyword">char</span> *p, *x;</span><br><span class="line"></span><br><span class="line">    <span class="built_in">snprintf</span>(filename,<span class="number">256</span>,<span class="string">"/proc/%d/stat"</span>,getpid());</span><br><span class="line">    <span class="keyword">if</span> ((fd = <span class="built_in">open</span>(filename,O_RDONLY)) == <span class="number">-1</span>) <span class="keyword">return</span> <span class="number">0</span>;</span><br><span class="line">    <span class="keyword">if</span> (<span class="built_in">read</span>(fd,buf,<span class="number">4096</span>) &lt;= <span class="number">0</span>) &#123;</span><br><span class="line">        <span class="built_in">close</span>(fd);</span><br><span class="line">        <span class="keyword">return</span> <span class="number">0</span>;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="built_in">close</span>(fd);</span><br><span class="line"></span><br><span class="line">    p = buf;</span><br><span class="line">    <span class="comment">// RSS 在proc/*/stat 下的第二十四个</span></span><br><span class="line">    count = <span class="number">23</span>; <span class="comment">/* RSS is the 24th field in /proc/&lt;pid&gt;/stat */</span></span><br><span class="line">    <span class="keyword">while</span>(p &amp;&amp; count--) &#123;</span><br><span class="line">        p = <span class="built_in">strchr</span>(p,<span class="string">' '</span>);</span><br><span class="line">        <span class="keyword">if</span> (p) p++;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">if</span> (!p) <span class="keyword">return</span> <span class="number">0</span>;</span><br><span class="line">    x = <span class="built_in">strchr</span>(p,<span class="string">' '</span>);</span><br><span class="line">    <span class="keyword">if</span> (!x) <span class="keyword">return</span> <span class="number">0</span>;</span><br><span class="line">    *x = <span class="string">'\0'</span>;</span><br><span class="line"></span><br><span class="line">    rss = strtoll(p,<span class="literal">NULL</span>,<span class="number">10</span>);</span><br><span class="line">    rss *= page;</span><br><span class="line">    <span class="keyword">return</span> rss;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<h2 id="zmalloc-get-memory-size"><a href="#zmalloc-get-memory-size" class="headerlink" title="zmalloc_get_memory_size"></a>zmalloc_get_memory_size</h2><p>得到物理内存的大小，直接读页数以及页大小， 相乘即可。<br><figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">size_t</span> zmalloc_get_memory_size(<span class="keyword">void</span>) &#123;</span><br><span class="line">    <span class="keyword">return</span> (<span class="keyword">size_t</span>)sysconf(_SC_PHYS_PAGES) * (<span class="keyword">size_t</span>)sysconf(_SC_PAGESIZE);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<h2 id="内存信息"><a href="#内存信息" class="headerlink" title="内存信息"></a>内存信息</h2><p>内存的各种信息， 在/proc/[pid]/smaps里面都可以查到， 比如上面的rss. /proc/self/smaps和/proc/[pid]/smaps完全等价。需要注意的一点是这里的单位是kb。<br><figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">size_t</span> zmalloc_get_smap_bytes_by_field(<span class="keyword">char</span> *field, <span class="keyword">long</span> pid) &#123;</span><br><span class="line">    <span class="keyword">char</span> <span class="built_in">line</span>[<span class="number">1024</span>];</span><br><span class="line">    <span class="keyword">size_t</span> bytes = <span class="number">0</span>;</span><br><span class="line">    <span class="keyword">int</span> flen = <span class="built_in">strlen</span>(field);</span><br><span class="line">    FILE *fp;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">if</span> (pid == <span class="number">-1</span>) &#123;</span><br><span class="line">        fp = fopen(<span class="string">"/proc/self/smaps"</span>,<span class="string">"r"</span>);</span><br><span class="line">    &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">        <span class="keyword">char</span> filename[<span class="number">128</span>];</span><br><span class="line">        <span class="built_in">snprintf</span>(filename,<span class="keyword">sizeof</span>(filename),<span class="string">"/proc/%ld/smaps"</span>,pid);</span><br><span class="line">        fp = fopen(filename,<span class="string">"r"</span>);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">if</span> (!fp) <span class="keyword">return</span> <span class="number">0</span>;</span><br><span class="line">    <span class="keyword">while</span>(fgets(<span class="built_in">line</span>,<span class="keyword">sizeof</span>(<span class="built_in">line</span>),fp) != <span class="literal">NULL</span>) &#123;</span><br><span class="line">        <span class="keyword">if</span> (<span class="built_in">strncmp</span>(<span class="built_in">line</span>,field,flen) == <span class="number">0</span>) &#123;</span><br><span class="line">            <span class="keyword">char</span> *p = <span class="built_in">strchr</span>(<span class="built_in">line</span>,<span class="string">'k'</span>);</span><br><span class="line">            <span class="keyword">if</span> (p) &#123;</span><br><span class="line">                *p = <span class="string">'\0'</span>;</span><br><span class="line">                bytes += strtol(<span class="built_in">line</span>+flen,<span class="literal">NULL</span>,<span class="number">10</span>) * <span class="number">1024</span>;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    fclose(fp);</span><br><span class="line">    <span class="keyword">return</span> bytes;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<h1 id="总结"><a href="#总结" class="headerlink" title="总结"></a>总结</h1><p>总体来说，Redis的内存管理并不是很复杂，仅仅是对标准库的一些函数进行在一次的封装并增加了一些其他功能。</p>

    </div>

    
    
    

      <footer class="post-footer">

        


        
    <div class="post-nav">
      <div class="post-nav-item">
    <a href="/2020/05/31/Redis-%E7%AE%80%E5%8D%95%E5%8A%A8%E6%80%81%E5%AD%97%E7%AC%A6%E4%B8%B2/" rel="prev" title="Redis 简单动态字符串">
      <i class="fa fa-chevron-left"></i> Redis 简单动态字符串
    </a></div>
      <div class="post-nav-item">
    <a href="/2020/06/01/Redis-%E9%93%BE%E8%A1%A8/" rel="next" title="Redis 链表">
      Redis 链表 <i class="fa fa-chevron-right"></i>
    </a></div>
    </div>
      </footer>
    
  </article>
  
  
  

  </div>


          </div>
          

<script>
  window.addEventListener('tabs:register', () => {
    let activeClass = CONFIG.comments.activeClass;
    if (CONFIG.comments.storage) {
      activeClass = localStorage.getItem('comments_active') || activeClass;
    }
    if (activeClass) {
      let activeTab = document.querySelector(`a[href="#comment-${activeClass}"]`);
      if (activeTab) {
        activeTab.click();
      }
    }
  });
  if (CONFIG.comments.storage) {
    window.addEventListener('tabs:click', event => {
      if (!event.target.matches('.tabs-comment .tab-content .tab-pane')) return;
      let commentClass = event.target.classList[1];
      localStorage.setItem('comments_active', commentClass);
    });
  }
</script>

        </div>
          
  
  <div class="toggle sidebar-toggle">
    <span class="toggle-line toggle-line-first"></span>
    <span class="toggle-line toggle-line-middle"></span>
    <span class="toggle-line toggle-line-last"></span>
  </div>

  <aside class="sidebar">
    <div class="sidebar-inner">

      <ul class="sidebar-nav motion-element">
        <li class="sidebar-nav-toc">
          Table of Contents
        </li>
        <li class="sidebar-nav-overview">
          Overview
        </li>
      </ul>

      <!--noindex-->
      <div class="post-toc-wrap sidebar-panel">
          <div class="post-toc motion-element"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#功能"><span class="nav-number">1.</span> <span class="nav-text">功能</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#函数分析"><span class="nav-number">2.</span> <span class="nav-text">函数分析</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#zmalloc-default-oom"><span class="nav-number">2.1.</span> <span class="nav-text">zmalloc_default_oom</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#内存统计函数"><span class="nav-number">2.2.</span> <span class="nav-text">内存统计函数</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#zmalloc-zcolloc-zrealloc-zfree"><span class="nav-number">2.3.</span> <span class="nav-text">zmalloc zcolloc zrealloc zfree</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#zstrup"><span class="nav-number">2.4.</span> <span class="nav-text">zstrup</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#zmalloc-used-memory"><span class="nav-number">2.5.</span> <span class="nav-text">zmalloc_used_memory</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#zmalloc-get-rss"><span class="nav-number">2.6.</span> <span class="nav-text">zmalloc_get_rss</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#zmalloc-get-memory-size"><span class="nav-number">2.7.</span> <span class="nav-text">zmalloc_get_memory_size</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#内存信息"><span class="nav-number">2.8.</span> <span class="nav-text">内存信息</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#总结"><span class="nav-number">3.</span> <span class="nav-text">总结</span></a></li></ol></div>
      </div>
      <!--/noindex-->

      <div class="site-overview-wrap sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
  <p class="site-author-name" itemprop="name">Z.J. Jiang</p>
  <div class="site-description" itemprop="description">about the single image super-resolution and face hallucination</div>
</div>
<div class="site-state-wrap motion-element">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
          <a href="/archives/">
        
          <span class="site-state-item-count">42</span>
          <span class="site-state-item-name">posts</span>
        </a>
      </div>
      <div class="site-state-item site-state-categories">
            <a href="/categories/">
          
        <span class="site-state-item-count">11</span>
        <span class="site-state-item-name">categories</span></a>
      </div>
      <div class="site-state-item site-state-tags">
            <a href="/tags/">
          
        <span class="site-state-item-count">1</span>
        <span class="site-state-item-name">tags</span></a>
      </div>
  </nav>
</div>
  <div class="links-of-author motion-element">
      <span class="links-of-author-item">
        <a href="https://github.com/jzijin" title="GitHub → https:&#x2F;&#x2F;github.com&#x2F;jzijin" rel="noopener" target="_blank"><i class="fa fa-fw fa-github"></i>GitHub</a>
      </span>
      <span class="links-of-author-item">
        <a href="/atom.xml" title="RSS → &#x2F;atom.xml"><i class="fa fa-fw fa-rss"></i>RSS</a>
      </span>
  </div>


  <div class="links-of-blogroll motion-element">
    <div class="links-of-blogroll-title">
      <i class="fa fa-fw fa-link"></i>
      Links
    </div>
    <ul class="links-of-blogroll-list">
        <li class="links-of-blogroll-item">
          <a href="http://www.njust.edu.cn/" title="http:&#x2F;&#x2F;www.njust.edu.cn" rel="noopener" target="_blank">南京理工大学</a>
        </li>
        <li class="links-of-blogroll-item">
          <a href="http://ehall.njust.edu.cn/new/index.html" title="http:&#x2F;&#x2F;ehall.njust.edu.cn&#x2F;new&#x2F;index.html" rel="noopener" target="_blank">南京理工大学智慧服务</a>
        </li>
        <li class="links-of-blogroll-item">
          <a href="http://lib.njust.edu.cn/" title="http:&#x2F;&#x2F;lib.njust.edu.cn&#x2F;" rel="noopener" target="_blank">南京理工大学图书馆</a>
        </li>
    </ul>
  </div>

      </div>

    </div>
  </aside>
  <div id="sidebar-dimmer"></div>


      </div>
    </main>

    <footer class="footer">
      <div class="footer-inner">
        

<div class="copyright">
  
  &copy; 
  <span itemprop="copyrightYear">2022</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">Z.J. Jiang</span>
</div>
  <div class="powered-by">Powered by <a href="https://hexo.io/" class="theme-link" rel="noopener" target="_blank">Hexo</a> v4.2.0
  </div>
  <span class="post-meta-divider">|</span>
  <div class="theme-info">Theme – <a href="https://pisces.theme-next.org/" class="theme-link" rel="noopener" target="_blank">NexT.Pisces</a> v7.6.0
  </div>

        








      </div>
    </footer>
  </div>

  
  <script src="/lib/anime.min.js"></script>
  <script src="/lib/velocity/velocity.min.js"></script>
  <script src="/lib/velocity/velocity.ui.min.js"></script>

<script src="/js/utils.js"></script>

<script src="/js/motion.js"></script>


<script src="/js/schemes/pisces.js"></script>


<script src="/js/next-boot.js"></script>




  















  

  
      
<script type="text/x-mathjax-config">
    MathJax.Ajax.config.path['mhchem'] = '//cdn.jsdelivr.net/npm/mathjax-mhchem@3';

  MathJax.Hub.Config({
    tex2jax: {
      inlineMath: [ ['$', '$'], ['\\(', '\\)'] ],
      processEscapes: true,
      skipTags: ['script', 'noscript', 'style', 'textarea', 'pre', 'code']
    },
    TeX: {
        extensions: ['[mhchem]/mhchem.js'],
      equationNumbers: {
        autoNumber: 'AMS'
      }
    }
  });

  MathJax.Hub.Register.StartupHook('TeX Jax Ready', function() {
    MathJax.InputJax.TeX.prefilterHooks.Add(function(data) {
      if (data.display) {
        var next = data.script.nextSibling;
        while (next && next.nodeName.toLowerCase() === '#text') {
          next = next.nextSibling;
        }
        if (next && next.nodeName.toLowerCase() === 'br') {
          next.parentNode.removeChild(next);
        }
      }
    });
  });

  MathJax.Hub.Queue(function() {
    var all = MathJax.Hub.getAllJax(), i;
    for (i = 0; i < all.length; i += 1) {
      element = document.getElementById(all[i].inputID + '-Frame').parentNode;
      if (element.nodeName.toLowerCase() == 'li') {
        element = element.parentNode;
      }
      element.classList.add('has-jax');
    }
  });
</script>
<script>
  NexT.utils.getScript('//cdn.jsdelivr.net/npm/mathjax@2/MathJax.js?config=TeX-AMS-MML_HTMLorMML', () => {
    MathJax.Hub.Typeset();
  }, window.MathJax);
</script>

    

  

</body>
</html>
